package com.briup.jd2511.jd2511bookstore.controller;

import com.briup.jd2511.jd2511bookstore.response.Result;
import com.briup.jd2511.jd2511bookstore.utils.PathUtils;
import com.briup.jd2511.jd2511bookstore.utils.UploadOSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Objects;

@Slf4j
@RestController
public class UploadController {
    @Autowired
    private UploadOSSUtils uploadOSSUtils;

    @PostMapping("/upload")
    public Result<String> upload(@RequestPart("img") MultipartFile image) throws IOException {
        log.info("上传图片:{}", image);
        // 上传上来的图片的文件位置： /Users/mastercgx/Desktop/image
//        String path = "/Users/mastercgx/Desktop/image";
//        // 获取上传的图片的名字
//        String fn = image.getOriginalFilename();
//        // 先获取文件的拓展名字
//        String ext = fn.substring(fn.lastIndexOf("."));
//        // 将名字和uuid拼接起来，保证其唯一性
//        String newName = UUID.randomUUID().toString() + ext;
//
//        // 转存到指定位置
//        image.transferTo(new File(path,newName));

        // 本地存储
        // String url = UploadUtils.fileToLocal(image);

        // 七牛云存储
        //1.根据上传的源文件名，生成唯一的文件路径，格式：yyyy/MM/dd/UUID.文件后缀
        String filePath =
                PathUtils.generateFilePath(Objects.requireNonNull(image.getOriginalFilename()));

        //2.调用工具类，上传文件
        String url = uploadOSSUtils.uploadOss(image, filePath);
        log.info("上传成功，访问地址为：{}", url);
        return Result.success(url);
    }
}
